package com.smalljj.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Window;
import android.widget.TextView;

import com.smalljj.comm.Constants;

/**
 * 更新/升级
 * 
 * @author Administrator
 * 
 */
public class UpdateActivity extends Activity {

	private ProgressDialog mProgressDialog;

	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

	public static final String SD_SAVE_DIR = "jjer";// 文件下载到手机目录

	// 定义要下载的文件名
	private String fileName;

	private String fileURL;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileURL() {
		return fileURL;
	}

	public void setFileURL(String fileURL) {
		this.fileURL = fileURL;
	}

	File rootDir = Environment.getExternalStorageDirectory();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去除标题
		setContentView(R.layout.update);

		Bundle bundle = this.getIntent().getExtras();
		setFileName(bundle.getString("newVersion") + ".apk");
		setFileURL(Constants.DOWNLOADURL + fileName);

		TextView tv = new TextView(this);
		tv.setText("Android Download File With Progress Bar");
		// 检查下载目录是否存在
		checkAndCreateDirectory("/" + SD_SAVE_DIR);

		// 执行asynctask
		new DownloadFileAsync().execute(getFileURL());
	}

	class DownloadFileAsync extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

		@Override
		protected String doInBackground(String... aurl) {
			try {
				final File file = new File(rootDir + "/" + SD_SAVE_DIR + "/",
						getFileName());
				// 连接地址
				URL u = new URL(getFileURL());
				HttpURLConnection connection = (HttpURLConnection) u
						.openConnection();
				connection.setRequestMethod("GET");
				connection.setDoOutput(true);
				connection.connect();

				// 计算文件长度
				int lenghtOfFile = connection.getContentLength();
				FileOutputStream fos = new FileOutputStream(file);
				InputStream ins = connection.getInputStream();
				// 下载的代码
				byte[] buffer = new byte[1024];
				int len1 = 0;
				long total = 0;
				while ((len1 = ins.read(buffer)) > 0) {
					total += len1; // total = total + len1
					publishProgress("" + (int) ((total * 100) / lenghtOfFile));
					fos.write(buffer, 0, len1);
				}
				fos.close();

				// 安装
				Intent intent = new Intent();
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setAction(android.content.Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(file),
						"application/vnd.android.package-archive");
				startActivity(intent);

			} catch (Exception e) {
			}
			return null;
		}

		protected void onProgressUpdate(String... progress) {
			mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		@Override
		protected void onPostExecute(String unused) {
			dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
	}

	public void checkAndCreateDirectory(String dirName) {
		File new_dir = new File(rootDir + dirName);
		if (!new_dir.exists()) {
			new_dir.mkdirs();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("文件下载中...");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
}